package com.boot.admin.modules.sys.ai.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * Web MVC配置 - 用于处理静态资源访问
 *
 * @author 李飞洋
 * @date 2025/9/24
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${qiniu.tts.audio.base-path}")
    private String audioBasePath;

    @Value("${ai.image.base-path:images}")
    private String imageBasePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置音频文件静态资源访问
        try {
            String resourcePath = getResourcePath();

            // 音频文件访问
            registry.addResourceHandler("/" + audioBasePath + "/**")
                    .addResourceLocations(resourcePath + audioBasePath + "/");

            // 图片文件访问 - 新增功能
            registry.addResourceHandler("/" + imageBasePath + "/**")
                    .addResourceLocations(resourcePath + imageBasePath + "/")
                    .setCachePeriod(3600); // 设置缓存1小时

        } catch (Exception e) {
            // 如果出现异常，使用默认配置
            registry.addResourceHandler("/" + audioBasePath + "/**")
                    .addResourceLocations("classpath:/" + audioBasePath + "/");

            registry.addResourceHandler("/" + imageBasePath + "/**")
                    .addResourceLocations("classpath:/" + imageBasePath + "/")
                    .setCachePeriod(3600);
        }
    }

    /**
     * 获取resources目录路径
     */
    private String getResourcePath() throws Exception {
        try {
            // 在开发环境中，获取src/main/resources路径
            ClassPathResource resource = new ClassPathResource("");
            File resourceDir = resource.getFile().getParentFile();
            return "file:" + new File(resourceDir, "classes").getAbsolutePath() + "/";
        } catch (Exception e) {
            // 如果是打包后的环境，使用当前工作目录下的resources
            String resourcePath = System.getProperty("user.dir") + "/src/main/resources";

            // 如果resources不存在，创建并使用它
            File resourceDir = new File(resourcePath);
            if (!resourceDir.exists()) {
                resourceDir = new File(System.getProperty("user.dir") + "/resources");
                if (!resourceDir.exists()) {
                    resourceDir.mkdirs();
                }
                resourcePath = resourceDir.getAbsolutePath();
            }
            return "file:" + resourcePath + "/";
        }
    }
}